class JobsController < ApplicationController

  skip_before_filter :require_login, :only => [:new, :create]

  def index
    @jobs = current_user.jobs.completed
  end

  def show
    @job = current_user.jobs.find(params[:id])
    respond_to do |format|
      format.html
      format.svg { render :text => Spectrum.new(@job).to_svg(params) }
    end
  end

  def tree
    @job = current_user.jobs.find(params[:id])
  end

  def new
    @job = Job.new(:measurement_error   => APP_CONFIG['default_measurement_error'],
                   :intensity_threshold => APP_CONFIG['default_intensity_threshold'],
                   :cuts                => APP_CONFIG['default_cuts'],
                   :rr                  => APP_CONFIG['default_rr'])
    source = dispatch_source(params[:source])
    session[:source] = source.to_s
    render source
  end

  def edit
    @job = current_user.jobs.find(params[:id])

    if @job.completed
      @fragment_candidates = @job.fragment_candidates(params)
      @peaks = @job.peaks
      flash[:notice] = t('notifications.jobs.edit.register') if current_user.temporary_user?
    else
      respond_to do |format|
        format.html { render :calculating }
        format.js { render :nothing => true, :status => 204 }
      end
    end
  end

  def create
    create_a_new_user_and_log_in unless logged_in?
    @job = current_user.jobs.new(params[:job])

    if @job.save
      Delayed::Job.enqueue(FidWorkerJob.new(@job.id))
      redirect_to edit_job_url(@job)
    else
      render dispatch_source(session[:source])
    end
  end

  def destroy
    @job = current_user.jobs.find(params[:id])
    if @job.destroy
      redirect_to jobs_url, :notice => t('notifications.jobs.destroy.success')
    end
  end

  def update
    @job = current_user.jobs.find(params[:id])
    @job.update_selected_fragments(params[:peaks].values)
    redirect_to job_url(@job)
  end

  private

  def create_a_new_user_and_log_in
    user = User.create!
    reset_session
    session[:user_id] = user.id
    set_current_user
  end

  def dispatch_source(source)
    case source
    when "kegg" then :kegg
    when "mol" then :mol
    when "marvin" then :marvin
    else :kegg
    end
  end
end
